<template>
  <van-popup v-model:show="data.show" position="bottom" @closed="cancel">
    <van-field v-model="data.searchVal" placeholder="搜索" @update:model-value="search" v-if="isSearch" input-align="left" />
    <van-picker v-bind="$attrs" :columns="data.columnsData" :columns-field-names="columnsFieldNames" show-toolbar @cancel="cancel" @confirm="onConfirm" @change="change" />
  </van-popup>
</template>

<script setup lang="ts">
//更新发送model
const emit = defineEmits(['update:modelValue', 'confirm', 'change', 'cancel', 'click'])

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  columns: {
    type: Array<object | number | string>,
    default: function () {
      return []
    }
  },

  columnsFieldNames: {
    type: Object,
    default: function () {
      return { text: 'text', value: 'value' }
    }
  },
  isSearch: {
    type: Boolean,
    default: false
  },

  searchPh: {
    type: String,
    default: '输入搜索信息'
  }
})
interface Config {
  show: boolean
  searchVal: string
  columnsData: Array<any>
  resultValue: string
  default_index: number // 默认选中项索引
}
const data: Config = reactive({
  show: false,
  searchVal: '',
  columnsData: [],
  resultValue: '',
  default_index: 0 // 默认选中项索引
})

//因为props的数据是只读，不能用于绑定popup的model，所以需要重新定义赋值
watch(
  () => props.modelValue,
  newVal => {
    data.show = newVal
  },
  {
    immediate: true,
    deep: true
  }
)

//搜索
const search = (val: string) => {
  if (val) {
    data.columnsData = props.columns.filter(item => {
      const res = item[props['columnsFieldNames'].text]
      return res.indexOf(val) > -1
    })
  } else {
    data.columnsData = JSON.parse(JSON.stringify(props.columns))
  }
}
//操作
const onConfirm = (value: any) => {
  let val = ''
  if (value) {
    val = value.selectedValues[0]
  }
  data.resultValue = val
  emit('confirm', value, val)
  emit('update:modelValue', false)
}
const change = (value: any) => {
  let val = ''
  if (value) {
    val = value.selectedValues[0]
  }
  emit('change', value, val)
}
const cancel = () => {
  emit('cancel')
  emit('update:modelValue', false)
}

watch(
  () => data.resultValue,
  () => {
    data.searchVal = ''
    data.columnsData = JSON.parse(JSON.stringify(props.columns))
  },
  {
    immediate: true,
    deep: true
  }
)
</script>

<style lang="scss" scoped>
.dh-field {
  padding: 0 16px;
  background: #fff;
  .dh-cell.van-cell {
    padding: 10px 0;
  }
  .dh-cell.van-cell--required::before {
    left: -8px;
  }
  .van-popup {
    border-radius: 20px 20px 0 0;
  }
}
</style>
